package com.timber.util;

import javax.swing.event.EventListenerList;
public class SLDataChangeListenerMgr {

	protected EventListenerList listenerList = new EventListenerList();

	/**
	 * Adds a listener to the list that's notified by fire... methods
	 * 
	 */
	public void addSLDataChangeListener(java.util.EventListener l) {
		listenerList.add(java.util.EventListener.class, l);
	}

	/**
	 * Removes listener from the list
	 * 
	 */
	public void removeSLDataChangeListener(java.util.EventListener l) {
		listenerList.remove(java.util.EventListener.class, l);
	}

	/**
	 * 
	 * reason: SLDataChangeEvent.RECORD_UPDATE
	 */
	public void fireSLDataUpdate(SLDataObject o) {
		fireSLDataEvent(o, SLDataChangeEvent.RECORD_UPDATE);
	}

	/**
	 * 
	 * reason: SLDataChangeEvent.RECORD_ADD
	 */
	public void fireSLDataAdd(SLDataObject o) {
		fireSLDataEvent(o, SLDataChangeEvent.RECORD_ADD);
	}

	/**
	 * 
	 * reason: SLDataChangeEvent.RECORD_DELETE
	 */
	public void fireSLDataDelete(SLDataObject o) {
		fireSLDataEvent(o, SLDataChangeEvent.RECORD_DELETE);
	}

	/**
	 * 
	 * notify listeners with DATA_CHANGE event
	 */
	public void fireSLDataChange(Object o) {
		fireSLDataEvent(o, SLDataChangeEvent.DATA_CHANGE);
	}

	/**
	 * create SLDataChangeEvent with Object(o) and Reason(r) and notify
	 * listeners
	 */
	public void fireSLDataEvent(Object o, int r) {
		SLDataChangeEvent ev = new SLDataChangeEvent(this, o, r);
		fireSLDataChangeEvent(ev);
	}

	/**
	 * notify listeners of event
	 */
	public void fireSLDataChangeEvent(SLDataChangeEvent ev) {
		Object[] listeners = listenerList.getListenerList();
		/*
		 * Process the listeners last to first, notifying those that are
		 * interested in this event listeners are stored in pairs ( type,
		 * listener ) so skip every other cell
		 */
		for (int i = listeners.length - 2; i >= 0; i -= 2) {
			// if (listeners[i] == SLDataChangeListener.class)
			((SLDataChangeListener) listeners[i + 1]).onDataChange(ev);
		}
	}

	/**
	 * check if anybody listening
	 */
	public boolean anyListeners() {
		return (listenerList.getListenerList().length > 0 ? true : false);
	}
}
